package ee.rsi2m.goproject.view;


import ee.rsi2m.goproject.R;
import ee.rsi2m.goproject.service.GoStoneThread;
import ee.rsi2m.goproject.service.SurfaceViewThread;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GoStoneView extends SurfaceView implements SurfaceHolder.Callback {

	private GoStoneThread thread;
	private int x = 20;
	private int y = 20;
	Paint paint = new Paint();
	int width;
	int height;

	public GoStoneView(Context context) {
		super(context);
		getHolder().addCallback(this);
		thread = new GoStoneThread(getHolder(), this);
		setFocusable(true);

	}

	@Override
	public void onDraw(Canvas canvas) {
		// Test - drawing a single stone;

		Bitmap scratch = BitmapFactory.decodeResource(getResources(),
				R.drawable.black32);
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(scratch, x - (scratch.getWidth() / 2),
				y - (scratch.getHeight() / 2), null);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		x = (int) event.getX();
		y = (int) event.getY();
		return true;
	}

	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();

	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		thread.setRunning(false);
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
				// we will try it again and again...
			}
		}

	}
}
